package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.profix}")
    String profix;
    //    @Value("${file.oss.endpoint}")
//    String endpoint;
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = multipartFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(profix, filename + profix, multipartFile.getInputStream());
            log.info("fileId: {}", fileId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) (0));
        wmMaterial.setIsCollection((short) 0);
        // 设置文件id
        wmMaterial.setUrl(fileId);
        // 当前线程中获取用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "用户当前未登录");
        }
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite + fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //检查参数
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //收藏
        if (dto.getIsCollection() == 1 && dto.getIsCollection() != null) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "当前自媒体用户未登录");
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageReq, wrapper);
        // 处理图片
        List<WmMaterial> wmMaterials = resultPage.getRecords();
        for (WmMaterial material : wmMaterials) {
            material.setUrl(webSite + material.getUrl());
        }
        //封装结果
        PageResponseResult responseResult = new PageResponseResult(dto.getSize(), dto.getPage(), (int) resultPage.getTotal());
        responseResult.setData(wmMaterials);
        //返回数据
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "自媒体用户未登录");
        }
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "该图片已经被引用无法删除");
        }
        // 删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        // 删除素材库
        removeById(id);
        // 返回结果
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检查参数
        if (id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
            //2.更新状态
            //获取当前用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getUserId,user.getId())
                .eq(WmMaterial::getId,id));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
